package org.luxor.commons.jdbc.plugin.dynamic.datasource;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.luxor.commons.core.exception.BaseException;
import org.luxor.commons.core.utils.CollectionUtils;
import org.luxor.commons.core.utils.encrypt.PbeEncryptUtils;
import org.luxor.commons.jdbc.plugin.dynamic.properties.DataSourceProperty;
import org.luxor.commons.jdbc.plugin.dynamic.properties.hikari.HikariCpConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.jdbc.DataSourceInitializationMode;
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.lang.reflect.Method;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 数据源创建器
 *
 * @author TaoYu
 * @since 2.3.0
 */
public class DynamicDataSourceCreator implements ApplicationContextAware {

    private static final Logger log = LoggerFactory.getLogger(DynamicDataSourceCreator.class);

    /**
     * 解密公匙(如果未设置默认使用全局的)
     */
    private String globalPublicKey = PbeEncryptUtils.DEFAULT_PUBLIC_KEY_STRING;

    /**
     * HikariCp数据源
     */
    private static final String HIKARI_DATASOURCE = "com.zaxxer.hikari.HikariDataSource";
    /**
     * JNDI数据源查找
     */
    private static final JndiDataSourceLookup JNDI_DATA_SOURCE_LOOKUP = new JndiDataSourceLookup();

    /**
     * 全局的Hikari线程池配置
     */
    private HikariCpConfig hikariGlobalConfig;

    /**
     * 是否存在hikari
     */
    private static Boolean hikariExists = false;

    static {
        // 初始化静态属性
        initStaticParams();
    }

    private ApplicationContext applicationContext;

    /**
     * 创建数据源
     *
     * @param dataSourceProperty 数据源信息
     * @return 数据源
     */
    public DataSource createDataSource(DataSourceProperty dataSourceProperty) {
        DataSource dataSource;

        log.info("dynamic-datasource - load a datasource named [{}] Started...", dataSourceProperty.getPollName());

        //如果是jndi数据源
        String jndiName = dataSourceProperty.getJndiName();
        if (!StringUtils.isEmpty(jndiName)) {
            dataSource = createJNDIDataSource(jndiName);
            return dataSource;
        }

        Class<? extends DataSource> type = dataSourceProperty.getType();
        if (type == null) {
            if (hikariExists) {
                dataSource = createHikariDataSource(dataSourceProperty);
            } else {
                dataSource = createBasicDataSource(dataSourceProperty);
            }
        } else if (HIKARI_DATASOURCE.equals(type.getName())) {
            dataSource = createHikariDataSource(dataSourceProperty);
        } else {
            dataSource = createBasicDataSource(dataSourceProperty);
        }

        // 执行初始化建表SQL
        List<String> schemas = dataSourceProperty.getSchema();
        if (schemas != null) {
            for (String schema : schemas) {
                runScript(dataSource, schema, dataSourceProperty);
            }
        }

        // 执行初始化数据SQL
        List<String> datas = dataSourceProperty.getData();
        if (!CollectionUtils.isEmpty(datas)) {
            for (String data : datas) {
                runScript(dataSource, data, dataSourceProperty);
            }
        }
        return dataSource;
    }

    /**
     * 创建基础数据源
     *
     * @param dataSourceProperty 数据源参数
     * @return 数据源
     */
    public DataSource createBasicDataSource(DataSourceProperty dataSourceProperty) {
        try {
            if (StringUtils.isEmpty(dataSourceProperty.getPublicKey())) {
                dataSourceProperty.setPublicKey(globalPublicKey);
            }
            Object o1 = createMethod.invoke(null);
            Object o2 = typeMethod.invoke(o1, dataSourceProperty.getType());
            Object o3 = urlMethod.invoke(o2, dataSourceProperty.getUrl());
            Object o4 = usernameMethod.invoke(o3, dataSourceProperty.getUsername());
            Object o5 = passwordMethod.invoke(o4, dataSourceProperty.getPassword());
            Object o6 = driverClassNameMethod.invoke(o5, dataSourceProperty.getDriverClassName());
            return (DataSource) buildMethod.invoke(o6);
        } catch (Exception e) {
            throw new BaseException("dynamic-datasource create basic datasource named "
                    + dataSourceProperty.getPollName() + " error");
        }
    }

    /**
     * 创建JNDI数据源
     *
     * @param jndiName jndi数据源名称
     * @return 数据源
     */
    public DataSource createJNDIDataSource(String jndiName) {
        return JNDI_DATA_SOURCE_LOOKUP.getDataSource(jndiName);
    }

    /**
     * 创建Hikari数据源
     *
     * @param dataSourceProperty 数据源参数
     * @return 数据源
     */
    public DataSource createHikariDataSource(DataSourceProperty dataSourceProperty) {
        if (StringUtils.isEmpty(dataSourceProperty.getPublicKey())) {
            dataSourceProperty.setPublicKey(globalPublicKey);
        }
        Assert.notNull(dataSourceProperty.getDriverClassName(),"dirverClassName must not be null");

        HikariCpConfig hikariCpConfig = dataSourceProperty.getHikari();
        HikariConfig config = hikariCpConfig.toHikariConfig(hikariGlobalConfig);
        config.setUsername(dataSourceProperty.getUsername());
        config.setPassword(dataSourceProperty.getPassword());
        config.setJdbcUrl(dataSourceProperty.getUrl());
        config.setDriverClassName(dataSourceProperty.getDriverClassName());
        config.setPoolName(dataSourceProperty.getPollName());
        return new HikariDataSource(config);
    }

    /**
     * 执行SQL脚本文件
     *
     * @param dataSource         数据源
     * @param location           脚本文件
     * @param dataSourceProperty 数据源配置
     */
    private void runScript(DataSource dataSource, String location,
                           DataSourceProperty dataSourceProperty) {
        if (StringUtils.hasText(location)) {
            String platform = dataSourceProperty.getPlatform();
            if (!meetPlatform(location, platform)) {
                return;
            }
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
            populator.setContinueOnError(dataSourceProperty.isContinueOnError());
            populator.setSeparator(dataSourceProperty.getSeparator());

            if (dataSourceProperty.getSqlScriptEncoding() != null) {
                populator.setSqlScriptEncoding(dataSourceProperty.getSqlScriptEncoding().name());
            }

            Resource resource = applicationContext.getResource(location);
            if (resource.exists()) {
                if (!isEnabled(dataSource, dataSourceProperty)) {
                    log.debug("Initialization disabled (not running data scripts)");
                    return;
                }
                populator.addScript(resource);
                try {
                    DatabasePopulatorUtils.execute(populator, dataSource);
                } catch (Exception e) {
                    log.warn("execute sql error", e);
                }
            } else {
                log.warn("could not find schema or data file {}", location);
            }
        }
    }

    private static final String DEFALULT_PLATFORM = "all";
    private static final Pattern PLATFORM_PATTERN = Pattern.compile("^.*-(.*).sql$");

    private boolean meetPlatform(String location, String platform) {
        if (DEFALULT_PLATFORM.equals(platform)) {
            return true;
        }
        Matcher matcher = PLATFORM_PATTERN.matcher(location);
        if (matcher.find()) {
            String extractVal = matcher.group(1);
            if (platform.equals(extractVal)) {
                return true;
            }
        }
        return false;
    }

    private boolean isEnabled(DataSource dataSource, DataSourceProperty dataSourceProperty) {
        DataSourceInitializationMode mode = dataSourceProperty.getInitializationMode();
        if (mode == DataSourceInitializationMode.NEVER) {
            return false;
        }
        if (mode == DataSourceInitializationMode.EMBEDDED && !isEmbedded(dataSource)) {
            return false;
        }
        return true;
    }

    private boolean isEmbedded(DataSource dataSource) {
        try {
            return EmbeddedDatabaseConnection.isEmbedded(dataSource);
        } catch (Exception ex) {
            log.debug("Could not determine if datasource is embedded", ex);
            return false;
        }
    }

    private static Method createMethod;
    private static Method typeMethod;
    private static Method urlMethod;
    private static Method usernameMethod;
    private static Method passwordMethod;
    private static Method driverClassNameMethod;
    private static Method buildMethod;

    private static void initStaticParams() {
        //to support springboot 1.5 and 2.x
        Class<?> builderClass = null;
        try {
            builderClass = Class.forName("org.springframework.boot.jdbc.DataSourceBuilder");
        } catch (Exception ignored) {
        }
        if (builderClass == null) {
            try {
                builderClass = Class
                        .forName("org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder");
            } catch (Exception e) {
            }
        }
        if (builderClass != null) {
            try {
                createMethod = builderClass.getDeclaredMethod("create");
                typeMethod = builderClass.getDeclaredMethod("type", Class.class);
                urlMethod = builderClass.getDeclaredMethod("url", String.class);
                usernameMethod = builderClass.getDeclaredMethod("username", String.class);
                passwordMethod = builderClass.getDeclaredMethod("password", String.class);
                driverClassNameMethod = builderClass.getDeclaredMethod("driverClassName", String.class);
                buildMethod = builderClass.getDeclaredMethod("build");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            Class.forName(HIKARI_DATASOURCE);
            hikariExists = true;
        } catch (ClassNotFoundException ignored) {
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public String getGlobalPublicKey() {
        return globalPublicKey;
    }

    public void setGlobalPublicKey(String globalPublicKey) {
        this.globalPublicKey = globalPublicKey;
    }

    public HikariCpConfig getHikariGlobalConfig() {
        return hikariGlobalConfig;
    }

    public void setHikariGlobalConfig(HikariCpConfig hikariGlobalConfig) {
        this.hikariGlobalConfig = hikariGlobalConfig;
    }


}
